/**
 * Created by aa on 2016/5/17.
 */
//灰图操作类
function GrayImage(imgId){
    this.targetObj=document.getElementById(imgId);

    this.setGray=function(){
        var result=this.getGray();
        if(result!=null) {
            this.targetObj.src = result;
        }
    };

        //利用canvas绘制灰白图片
        this.getGray=function gray() {
            var imgObj=this.targetObj;
            if(this.targetObj==null){
                return null;
            }
            var canvas = document.createElement('canvas');
            var canvasContext = canvas.getContext('2d');

            var imgW = this.getNaturalWidth(imgObj).Width;
            var imgH = this.getNaturalWidth(imgObj).Height;
            canvas.width = imgW;
            canvas.height = imgH;

            canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

        for (var y = 0; y < imgPixels.height; y++) {
            for (var x = 0; x < imgPixels.width; x++) {
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg;
                imgPixels.data[i + 1] = avg;
                imgPixels.data[i + 2] = avg;
            }
        }
        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
    };

    //获取图片原始路径
    this.getNaturalWidth=function(img){
        var image = new Image();
        image.src = img.src
        var natural={};
        natural.Width = image.width
        natural.Height=image.height;
        return natural};
}
